/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controllers;

import binding.comments.CommentType;
import binding.comments.Comments;
import core.DBEntities;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.sql.SQLException;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.transform.dom.DOMSource;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
import utils.CommonUtils;
import utils.DefaultErrorHandler;
import utils.DomUtils;
import utils.XmlUtils;
import utils.XmlValidate;

public class CommentController extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String webPath = getServletContext().getRealPath("/");
            String xsdPath = webPath + "WEB-INF/classes/schemas/comments.xsd";
            String filePath = webPath + "WEB-INF/XmlDoc/Comments.xml";
            String xslPath = webPath + "WEB-INF/XslDoc/Comment.xsl";
            String action = request.getParameter("action");
            if (action.equals("COMMENT_DELETE")) {
                String comid = request.getParameter("comid");
                DBEntities.deleteComment(comid);
                Comments comlist = DBEntities.getListComments();
                XmlUtils.marshalXml(comlist, filePath);
                Map<String, Object> params = new LinkedHashMap<String, Object>();
                String proid = request.getParameter("proid");
                params.put("proid", CommonUtils.convertStringToInt(proid));
                params.put("propath", webPath + "WEB-INF/XmlDoc/Products.xml");
                params.put("userpath", webPath + "WEB-INF/XmlDoc/Users.xml");
                params.put("userdetailpath", webPath + "WEB-INF/XmlDoc/UserDetails.xml");
                params.put("type", "control");
                String result = XmlUtils.transformToString(webPath + "WEB-INF/XslDoc/Comment.xsl", webPath + "WEB-INF/XmlDoc/Comments.xml", params);
                out.write(result);

//                Object obj = XmlUtils.unMarshalXml(xsdPath, filePath, Comments.class);
//                if (obj != null && obj instanceof Comments) {
//                    Comments comlist = (Comments) obj;
//                    CommentType comType = null;
//                    for (CommentType r : comlist.getComment()) {
//                        if (comid.equals(String.valueOf(r.getId().intValue()))) {
//                            comType = r;
//                        }
//                    }
//                    if (comType != null) {
//                        comType.setIsActive(!comType.isIsActive());
//                    }
////
//
//                }
            } else if (action.equals("COMMENT_ADD")) {
                String uid = request.getParameter("uid");
                String proid = request.getParameter("proid");
                String text = request.getParameter("containtext");

                Integer userid = Integer.parseInt(uid);
                Integer productid = Integer.parseInt(proid);
                Integer rating = 1;
                Map<String, Object> pros = new LinkedHashMap<String, Object>();
                pros.put("UserId", userid);
                pros.put("ProductId", productid);
                pros.put("Comment", text);
                pros.put("Rating", rating);
                GregorianCalendar cldTimeStamp = new GregorianCalendar();
                cldTimeStamp.setTime(new Date());
                pros.put("Timestamp", DatatypeFactory.newInstance().newXMLGregorianCalendar(cldTimeStamp).toXMLFormat());
                pros.put("IsActive", true);

                //need to validate here
                Node doc = DomUtils.buildDomTree("http://xml.netbeans.org/schema/comments", "Comments", "Comment", pros);
                DefaultErrorHandler handler = new DefaultErrorHandler();
                XmlValidate.validate(xsdPath, new DOMSource(doc), handler);
                if (handler.isError()) {
                    String res = "<?xml version='1.0' encoding='UTF-8'?>";
                    res += "<error>" + handler.getErrorMessage() + "</error>";
                    response.setContentType("text/xml");
                    out.write(res);
                } else {
                    CommentType comType = new CommentType();
                    comType.setUserId(BigInteger.valueOf(userid));
                    comType.setProductId(BigInteger.valueOf(productid));
                    comType.setComment(text);
                    comType.setRating(BigInteger.valueOf(rating));
                    GregorianCalendar gTimeStamp = new GregorianCalendar();
                    gTimeStamp.setTime(new Date());
                    comType.setTimestamp(DatatypeFactory.newInstance().newXMLGregorianCalendar(gTimeStamp));
                    comType.setIsActive(true);
                    if (DBEntities.saveNewComment(comType)) {
                        Comments comlist = DBEntities.getListComments();
                        XmlUtils.marshalXml(comlist, filePath);
                        Map<String, Object> params = new LinkedHashMap<String, Object>();
                        params.put("type", "COMMENT_LOAD");
                        params.put("proid", productid);
                        params.put("propath", webPath + "WEB-INF/XmlDoc/Products.xml");
                        params.put("userpath", webPath + "WEB-INF/XmlDoc/Users.xml");
                        params.put("userdetailpath", webPath + "WEB-INF/XmlDoc/UserDetails.xml");
                        String result = XmlUtils.transformToString(webPath + "WEB-INF/XslDoc/Comment.xsl", webPath + "WEB-INF/XmlDoc/Comments.xml", params);
                        out.write(result);
                    }
                }



            }
        } catch (SAXException ex) {
            Logger.getLogger(CommentController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (DatatypeConfigurationException ex) {
            Logger.getLogger(CommentController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(CommentController.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        processRequest(request, response);

    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
